import ReactDOM from 'react-dom'

import './App.css'

// 初始化数据
let state: number[] = []
let hookIndex = 0

const useState = (initialState: number) => {
  state[hookIndex] = state[hookIndex] || initialState

  // 修改状态的函数
  let curHookIndex = hookIndex
  const setState = (value: number) => {
    state[curHookIndex] = value

    // 重新渲染组件
    render()
  }

  // 定义返回值类型
  type StateTuple = [number, (value: number) => void]
  const response: StateTuple = [state[hookIndex], setState]

  hookIndex++
  return response
}

function App() {
  // 创建自己的 useState
  const [age, setAge] = useState(100)
  const [count, setCount] = useState(88)

  const ageHandler = () => {
    setAge(age + 1)
  }

  const countHandler = () => {
    setCount(count + 1)
  }

  return (
    <div className="box">
      <h4>age：{age}</h4>
      <h4>count：{count}</h4>
      <button onClick={ageHandler}>+1</button>
      <button onClick={countHandler}>+1</button>
    </div>
  )
}

function render() {
  ReactDOM.render(<App />, document.getElementById('root'))

  // 重置 hookIndex 的值
  hookIndex = 0
}

render()
